<!--使用方法：
	引入到需要用到日历组件的地方，并不是任意位置。
	<calendar send-date='1992/7/3 -1' :is-solar='true' @getSelectDate='getDate'></calendar>
  titleValue: 表示需要传入的标题 默认为生日
  defaultString: 表示需要显示的信息，默认为空显示设置的send-data,若设置则显示设置信息需用v-model进行绑定
	send-date：表示需要传入的日期， -1表示时辰不清楚，其余的0-23分别表示0至23点
	is-solar： 表示是否是公历，true为公历，false为农历
	is-leap: 表示当前农历月份是否是闰月，true表示是闰月，false表示不是闰月
	cur-index: 表示当前是第几个日历组件，用于使用多个日历组件的情况。第一个就传0，第二个就传1，第三个就传2。。。
	@getSelectDate='getDate' ： 表示点击确定之后需要触发的事件，getDate是父组件需要接收的事件，用于接收选择的内容
	minSolarDate ：表示最小公历日期，不用设置农历，能自动判断公农历边界
	maxSolarDate : 表示最大公历日期，不用设置农历，能自动判断公农历边界
-->

<template>
  <div id="calendarComponent">
    <group :label-align="titleAlign">
      <cell :class="{'active':selectDateStr!='请选择日期'}"
        :title="titleValue"
        :value="selectDateStr"
        :value-align="valueAlign"
        is-link
        @click.native="showCalendar"
      ></cell>
    </group>

    <popup v-model="isShow">
      <div class="calendar-head">
        <button class="calendar-cancle" @click="hideCalendar">取消</button>
        <button class="calendar-confirm" @click="confirmDate">确定</button>
        <div class="calendar-nav">
          <button
            :class="['calendar-typeBtn', selectIndex == index ? 'calendar-active' : '']"
            @click="getSelectType(index)"
            v-for="(item, index) in selectContent"
            :key="index"
          >
            {{ item }}
          </button>
        </div>
      </div>

      <div class="calendar-scroll">
        <div class="calendar-pickArea"></div>
        <div class="calendar-mask-top"></div>
        <div class="calendar-mask-bottom"></div>
        <div class="calendar-scroll-col calendarYear">
          <div class="calendar-scroll-inner">
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item" v-for="(item, index) in yearArr" :key="index">
              {{ item }}
            </p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
          </div>
        </div>
        <div class="calendar-scroll-col calendarMonth">
          <div class="calendar-scroll-inner">
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item" v-for="(item, index) in monthArr" :key="index">
              {{ item }}
            </p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
          </div>
        </div>
        <div class="calendar-scroll-col calendarDay">
          <div class="calendar-scroll-inner">
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item" v-for="(item, index) in dayArr" :key="index">
              {{ item }}
            </p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
          </div>
        </div>
        <div class="calendar-scroll-col calendarHour">
          <div class="calendar-scroll-inner">
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item" v-for="(item, index) in hourArr" :key="index">
              {{ item }}
            </p>
            <p class="calendar-scroll-item">&nbsp;</p>
            <p class="calendar-scroll-item">&nbsp;</p>
          </div>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>

require('./iscroll-lite');
import calendar from './calendar.js';
import { Group, Cell, Popup } from 'vux';

export default {
  props: {
    // 左侧标题内容，默认“生日”
    titleValue:{
      type: String,
      default: '生日'
    },
    //传入日期。-1表示时辰不清楚，其它的则是0-23分别表示0点到23点。如果不传，则使用默认值
    birthDate: {
      type: String,
      default: '',    
    },
    // 右边内容默认显示的字符串，如果不传，则使用默认
    defaultStr:{
      type: String,
      default: '', 
    },
    // 默认初始日期
    defaultDate:{
      type: String,
      default: '1990/1/1 -1',
    },
    //是否是公历，true为公历，false为农历。如果不传，则使用默认值
    isSolar: {
      type: Boolean,
      default: true
    },
    //当前农历月份是否是闰月，默认false表示不是闰月，true表示是闰月。如果不传，则使用默认值
    isLeap: {
      type: Boolean,
      default: false
    },
    //最小日期,公历。如果不传，则使用默认值
    minSolarDate: {
      type: String,
      default: '1901/1/1'
    },
    //最大日期，公历。如果不传，则使用默认值
    maxSolarDate: {
      type: String,
      default: '2100/12/31'
    },
    //当前是引入的第几个日历组件。默认是只引入了一个，即为0。
    curIndex: {
      type: Number,
      default: 0
    },
    // 左边内容标题对齐方式
    titleAlign: {
      type: String,
      default: 'left'
    },
    // 右边值内容标题对齐方式
    valueAlign: {
      type: String,
      default: 'left'
    },
  },
  components: {
    Group,
    Cell,
    Popup
  },
  data: function() {
    return {
      sendDate: '',
      selectContent: ['公历', '农历'],
      selectIndex: 0, //公农历按钮选择的索引值，0表示公历，1表示农历
      selectArr: [], //年，月，日，时辰当前选择的索引值
      selectDateStr: '', //形如1992-08-01 时辰不清楚，用于显示用
      yearArr: [], //所有年份
      monthArr: [], //所有月份
      dayArr: [], //所有天数
      hourArr: [], //所有时辰
      itemHeight: 0, //每个列表的高度
      isShow: false, //是否显示日历组件，默认不显示
      scrollTarget: [], //滚动内容对象
      maxLunarDate: '', //最大农历日期
      minLunarDate: '', //最小农历日期
      canSwitch: true, //是否能够切换
    };
  },
  created: function() {
    if(this.birthDate == ''){
      this.sendDate = this.defaultDate;
    }else{
      this.sendDate = this.birthDate;
    }

    this.itemHeight = (document.body.offsetWidth / 750) * 100 * 0.8;

    this.judgeDateCorrect(this.sendDate);
    this.judgeDateCorrect(this.minSolarDate);
    this.judgeDateCorrect(this.maxSolarDate);

    this.setLunarDate();

    this.judgeOverstepDate();

    this.selectIndex = this.isSolar ? 0 : 1;

    this.initDateArr();
    this.dealSendDate();
  },
  watch:{
    birthDate:function(val){
      if(val == ''){
        this.sendDate = this.defaultDate;
      }else{
        this.sendDate = this.birthDate;
        this.initDateArr();
        this.dealSendDate(false);
      }
    },
    selectDateStr:function(val){
      
    }
  },
  mounted:function(){
    this.initScroll();
  },
  methods: {
    //判断日期格式是否正确
    judgeDateCorrect: function(date) {
      if (date.indexOf(':') != -1) {
        throw Error('传入的日期需要是yy/mm/dd -1的形式。请修改格式');
      } else if (
        date.indexOf('/') == -1 ||
        (date.indexOf('/') != -1 && date.split(' ')[0].split('/').length < 3)
      ) {
        throw Error('请确定日期格式是yy/mm/dd,而非yy-mm-dd');
      }
    },
    //设置最大,最小农历日期边界
    setLunarDate: function() {
      var min = this.minSolarDate.split('/');
      var max = this.maxSolarDate.split('/');
      var minDateObj = calendar.solar2lunar(min[0], min[1], min[2]);
      var maxDateObj = calendar.solar2lunar(max[0], max[1], max[2]);

      var minLunar = minDateObj.lYear + '/' + minDateObj.lMonth + '/' + minDateObj.lDay;
      var maxLunar = maxDateObj.lYear + '/' + maxDateObj.lMonth + '/' + maxDateObj.lDay;

      this.minLunarDate = minLunar;
      this.maxLunarDate = maxLunar;
    },
    //判断传入日期是否小于最小日期
    judgeOverstepDate: function() {
      var sendDateTime = new Date(this.sendDate.split(' ')[0]);
      var minDateTime = new Date(this.minSolarDate);
      if (sendDateTime <= minDateTime) {
        throw Error('传入日期不能小于最小设置日期，请重新设置！');
      }
    },
    //初始化滚动函数
    initScroll: function() {
      //初始化初始的位置
      var yearStartY = this.selectArr[0] * this.itemHeight;
      var monthStartY = this.selectArr[1] * this.itemHeight;
      var dayStartY = this.selectArr[2] * this.itemHeight;
      var hourStartY = this.selectArr[3] * this.itemHeight;

      //公用配置
      var options = {
        snap: '.calendar-scroll-item' //对齐的位置，相当于自动纠正每次移动的距离
        //scrollbars: true,//是否显示滚动条
      };
      //初始化滚动
      var yearScroll = new IScroll('.calendar-scroll>.calendarYear', options, this.curIndex);
      var monthScroll = new IScroll('.calendar-scroll>.calendarMonth', options, this.curIndex);
      var dayScroll = new IScroll('.calendar-scroll>.calendarDay', options, this.curIndex);
      var hourScroll = new IScroll('.calendar-scroll>.calendarHour', options, this.curIndex);

      this.fixMaxScrollY(yearScroll, 0);
      this.fixMaxScrollY(monthScroll, 1);
      this.fixMaxScrollY(dayScroll, 2);
      this.fixMaxScrollY(hourScroll, 3);

      //保存滚动对象
      if(this.scrollTarget.length > 0){
        this.$set(this.scrollTarget,0,yearScroll)
        this.$set(this.scrollTarget,1,monthScroll)
        this.$set(this.scrollTarget,2,dayScroll)
        this.$set(this.scrollTarget,3,hourScroll)
      }else{
        this.scrollTarget.push(yearScroll, monthScroll, dayScroll, hourScroll);
      }

      //滚动到指定的位置
      yearScroll.scrollTo(0, -yearStartY);
      monthScroll.scrollTo(0, -monthStartY);
      dayScroll.scrollTo(0, -dayStartY);
      hourScroll.scrollTo(0, -hourStartY);

      var that = this; //必须保存此时的上下文。
      yearScroll.on('scrollStart', function() {
        that.canSwitch = false;
      });
      yearScroll.on('scrollEnd', function() {
        //这里的函数不能写成箭头函数的形式
        that.fixPos(this, 0);
        that.fixConfine(dayScroll);
        that.canSwitch = true;
      });

      monthScroll.on('scrollStart', function() {
        that.canSwitch = false;
      });
      monthScroll.on('scrollEnd', function() {
        //这里的函数不能写成箭头函数的形式
        that.fixPos(this, 1);
        that.fixConfine(dayScroll);
        that.canSwitch = true;
      });

      dayScroll.on('scrollStart', function() {
        that.canSwitch = false;
      });
      dayScroll.on('scrollEnd', function() {
        //这里的函数不能写成箭头函数的形式
        that.fixPos(this, 2);
        that.fixConfine(dayScroll);
        that.canSwitch = true;
      });

      hourScroll.on('scrollStart', function() {
        that.canSwitch = false;
      });
      hourScroll.on('scrollEnd', function() {
        //这里的函数不能写成箭头函数的形式
        that.fixPos(this, 3);
        that.canSwitch = true;
      });
    },
    //纠正天数，比如选择1月31号之后，切换到2月，这时需要纠正2月份的天数和位置
    fixDayArr: function(target) {
      var curYear = this.selectArr[0] + 1900;
      var curMonth = this.selectArr[1] + 1;
      curMonth = curMonth > 12 ? 12 : curMonth;
      var oldDayIndex = this.selectArr[2];

      if (this.selectIndex) {
        //当前年份是否有闰月
        var leapMonth = calendar.leapMonth(curYear);
        //如果有闰月
        if (leapMonth) {
          //如果此时是大于或等于闰月的月份，则需要修正偏差1
          if (this.selectArr[1] >= leapMonth) {
            curMonth = this.selectArr[1];
          }
        }
      }
      //更新当前年月有多少天
      var newLength = this.getDayArr(curYear, curMonth, this.selectIndex);

      this.$nextTick(() => {
        //刷新天数滚动内容的边界，重新让计算天数的内容高度
        target.refresh();
        //如果选择的索引大于或等于当前天数的长度，则重新设置位置和索引。
        if (oldDayIndex > newLength - 1) {
          this.selectArr[2] = newLength - 1;
        } else {
          this.selectArr[2] = oldDayIndex;
        }
      });
    },
    //修复使用rem时有时选择位置不正确的情况
    fixPos: function(target, num) {
      var step = Math.abs(Math.round(target.y / this.itemHeight));
      var maxYearLen = this.yearArr.length;
      var maxMonthLen = this.monthArr.length;
      var maxDayLen = this.dayArr.length;
      var maxHourLen = this.hourArr.length;
      switch (num) {
        case 0:
          step = step > maxYearLen ? maxYearLen - 1 : step;
          break;
        case 1:
          step = step > maxMonthLen ? maxMonthLen - 1 : step;
          break;
        case 2:
          step = step > maxDayLen ? maxDayLen - 1 : step;
          break;
        case 3:
          step = step > maxHourLen ? maxHourLen - 1 : step;
          break;
      }
      var fixPos = step * this.itemHeight;
      target.y = fixPos;
      this.selectArr[num] = step;
      target.scrollTo(0, -fixPos);
    },
    //修复使用rem时最大滚动距离不准确的问题
    fixMaxScrollY: function(target, num) {
      var yearLen = this.yearArr.length - 1;
      var monthLen = this.monthArr.length - 1;
      var dayLen = this.dayArr.length - 1;
      var hourLen = this.hourArr.length - 1;

      switch (num) {
        case 0:
          target.maxScrollY = -Math.round(yearLen * this.itemHeight);
          break;
        case 1:
          target.maxScrollY = -Math.round(monthLen * this.itemHeight);
          break;
        case 2:
          target.maxScrollY = -Math.round(dayLen * this.itemHeight);
          break;
        case 3:
          target.maxScrollY = -Math.round(hourLen * this.itemHeight);
          break;
      }
    },
    /**
     * 选择的日期超出范围将自动矫正到最大或者最小的日期
     */
    fixConfine: function(target) {
      var minSolarArr = this.minSolarDate.split('/'); //最小公历数组
      var minLunarArr = this.minLunarDate.split('/'); //最小农历数组

      var maxSolarArr = this.maxSolarDate.split('/'); //最大公历数组
      var maxLunarArr = this.maxLunarDate.split('/'); //最大农历数组

      var minSolarTime = new Date(this.minSolarDate); //最小公历日期的时间戳
      var minLunarTime = new Date(this.minLunarDate); //最小农历日期的时间戳

      var maxSolarTime = new Date(this.maxSolarDate); //最大公历日期的时间戳
      var maxLunarTime = new Date(this.maxLunarDate); //最大农历日期的时间戳

      //判断最小农历是否有闰月
      var minLeapMonth = calendar.leapMonth(minLunarArr[0]);
      if (this.selectIndex && minLeapMonth && minLunarArr[1] > minLeapMonth) {
        minLunarArr[1] = Number(minLunarArr[1]) + 1;
      }
      //判断最大农历是否有闰月
      var maxLeapMonth = calendar.leapMonth(maxLunarArr[0]);
      if (this.selectIndex && maxLeapMonth && maxLunarArr[1] > maxLeapMonth) {
        maxLunarArr[1] = Number(maxLunarArr[1]) + 1;
      }

      //判断选择的日期是否有闰月
      var selectYear = this.selectArr[0] + 1900;
      var selectMonth = 0;
      var selectLeapMonth = calendar.leapMonth(selectYear);
      if (this.selectIndex && selectLeapMonth && this.selectArr[1] > selectLeapMonth) {
        selectMonth = this.selectArr[1];
      } else {
        selectMonth = this.selectArr[1] + 1;
      }

      var selectDay = this.selectArr[2] + 1;
      var selectTime = new Date(selectYear + '/' + selectMonth + '/' + selectDay);
      //选择的是农历
      if (this.selectIndex) {
        //最小农历日期修复
        if (minLunarTime >= selectTime) {
          this.dateFixScroll(minLunarArr);
        }
        //最大农历日期修复
        if (maxLunarTime <= selectTime) {
          this.dateFixScroll(maxLunarArr);
        }
      } else {
        //最小公历日期修复
        if (minSolarTime >= selectTime) {
          this.dateFixScroll(minSolarArr);
        }
        //最大公历日期修复
        if (maxSolarTime <= selectTime) {
          this.dateFixScroll(maxSolarArr);
        }
      }

      //修正天数
      this.fixDayArr(target);
    },
    //日期修复之后滚动到指定位置
    dateFixScroll: function(arr) {
      var perHeight = this.itemHeight;

      this.scrollTarget[0].scrollTo(0, -perHeight * (arr[0] - 1900));
      this.scrollTarget[1].scrollTo(0, -perHeight * (arr[1] - 1));
      this.scrollTarget[2].scrollTo(0, -perHeight * (arr[2] - 1));

      this.selectArr[0] = arr[0] - 1900;
      this.selectArr[1] = arr[1] - 1;
      this.selectArr[2] = arr[2] - 1;
    },
    //处理传过来的默认日期，处理成当前所在索引的数组的形式
    dealSendDate: function(status) {
      
      var target = this.sendDate.split(' ');

      var hourIndex = Number(target[1]) + 1; //时辰索引值

      var dateStr = target[0].split('/'); //默认日期的数组形式
      if (dateStr[0] < 1900 || dateStr[1] <= 0 || dateStr[2] <= 0) {
        throw Error('请确认传入时间是否正确！');
      }

      var minDateArr = this.minSolarDate.split('/'); //最小日期的数组形式

      var yearIndex = dateStr[0] - 1900;
      var leapMonth = calendar.leapMonth(yearIndex + 1900);
      var monthIndex = 0;
      //当前月份是否是闰月
      if (this.isLeap) {
        monthIndex = Number(dateStr[1]);
      } else {
        if (this.selectIndex && leapMonth && dateStr[1] > leapMonth) {
          monthIndex = Number(dateStr[1]);
        } else {
          monthIndex = Number(dateStr[1]) - 1;
        }
      }
      var dayIndex = dateStr[2] - 1;
      if(this.selectArr.length > 0){
        this.$set(this.selectArr,0,yearIndex)
        this.$set(this.selectArr,1,monthIndex)
        this.$set(this.selectArr,2,dayIndex)
        this.$set(this.selectArr,3,hourIndex)
      }else{
        this.selectArr.push(yearIndex, monthIndex, dayIndex, hourIndex);
      }
      this.getDayArr(dateStr[0], dateStr[1], this.selectIndex);
      var sendStatus = status == undefined ? false : status;
      this.getAllDateStr(sendStatus);
    },
    //切换到农历
    changeToLunarDate: function() {
      if (!this.canSwitch) return;
      var selectData = this.selectArr;
      var solaryear = selectData[0] + 1900; //公历年份
      var solarmonth = selectData[1] + 1;
      var solarday = selectData[2] + 1;
      var lunarDate = calendar.solar2lunar(solaryear, solarmonth, solarday); //返回的日期信息

      var leapMonth = calendar.leapMonth(lunarDate.lYear);

      var isLeap = lunarDate.isLeap; //本月是否是闰月

      var yearIndex = lunarDate.lYear - 1900;
      var monthIndex = 0;
      //如果有闰月
      if (leapMonth) {
        monthIndex = isLeap ? lunarDate.lMonth : lunarDate.lMonth - 1;
        monthIndex = lunarDate.lMonth > leapMonth ? lunarDate.lMonth : monthIndex;
      } else {
        monthIndex = lunarDate.lMonth - 1;
      }

      var dayIndex = lunarDate.lDay - 1;

      this.selectArr[0] = yearIndex;
      this.selectArr[1] = monthIndex;
      this.selectArr[2] = dayIndex;

      this.getDayArr(lunarDate.lYear, lunarDate.lMonth, this.selectIndex); //d

      this.scrollTarget[0].scrollTo(0, -yearIndex * this.itemHeight);
      this.scrollTarget[1].scrollTo(0, -monthIndex * this.itemHeight);
      this.scrollTarget[2].scrollTo(0, -dayIndex * this.itemHeight);

      this.fixMaxScrollY(this.scrollTarget[0], 0);
      this.fixMaxScrollY(this.scrollTarget[1], 1);
      this.fixMaxScrollY(this.scrollTarget[2], 2);
    },
    //切换到公历
    changeToSolarDate: function() {
      if (!this.canSwitch) return;

      var lunarDate = this.selectArr;
      var lunarYear = lunarDate[0] + 1900; //农历年

      var leapMonth = calendar.leapMonth(lunarYear); //闰几月，0表示没有闰月

      var lunarMonth = 0;
      if (lunarDate[1] >= 12) {
        lunarMonth = 12;
      } else {
        lunarMonth = lunarDate[1];
      }

      if (leapMonth) {
        var isLeap = this.monthArr[lunarMonth].indexOf('闰') != -1 ? true : false; //本月是否是闰月
        lunarMonth = lunarMonth >= leapMonth ? lunarMonth : lunarMonth + 1;
      } else {
        lunarMonth = lunarMonth >= 12 ? lunarMonth : lunarMonth + 1;
      }

      var lunarDay = lunarDate[2] + 1;

      var allDate = calendar.lunar2solar(lunarYear, lunarMonth, lunarDay, isLeap);

      var yearIndex = allDate.sYear - 1900;
      var monthIndex = allDate.sMonth - 1;
      var dayIndex = allDate.sDay - 1;

      this.selectArr[0] = yearIndex;
      this.selectArr[1] = monthIndex;
      this.selectArr[2] = dayIndex;

      this.getDayArr(allDate.sYear, allDate.sMonth, this.selectIndex);

      this.scrollTarget[0].scrollTo(0, -yearIndex * this.itemHeight);
      this.scrollTarget[1].scrollTo(0, -monthIndex * this.itemHeight);
      this.scrollTarget[2].scrollTo(0, -dayIndex * this.itemHeight);

      this.fixMaxScrollY(this.scrollTarget[0], 0);
      this.fixMaxScrollY(this.scrollTarget[1], 1);
      this.fixMaxScrollY(this.scrollTarget[2], 2);
    },
    //初始化日期
    initDateArr: function() {
      var yearData = [],
        monthData = [],
        hourData = ['时辰不清楚'];

      for (var i = 1900; i <= 2100; i++) {
        yearData.push(i);
      }
      for (var i = 1; i <= 12; i++) {
        monthData.push(i + '月');
      }
      for (var i = 0; i <= 23; i++) {
        if (i == 23) {
          hourData.push(`${i}点子时`);
        } else {
          hourData.push(`${i}点${calendar.Zhi[Math.ceil(i / 2)]}时`);
        }
      }
      this.yearArr = yearData;
      this.monthArr = monthData;
      this.hourArr = hourData;
    },
    //获取指定的年，月有多少天。添加农历年份可能有闰月的月份
    getDayArr: function(year, month, dateType) {
      var dayData = [];
      var monthDate = [];
      //如果当前是公历
      if (dateType == 0) {
        for (var i = 1; i <= 12; i++) {
          monthDate.push(i + '月');
        }
        for (var i = 1; i <= calendar.solarDays(year, month); i++) {
          dayData.push(i);
        }
      } else {
        //如果当前是农历
        var leapMonthStr = calendar.leapMonth(year); //如果是0表示没有闰月，其它的则是润几月
        //如果当前year是有闰月
        if (leapMonthStr) {
          //更新月份
          for (var i = 1; i <= 12; i++) {
            if (i == leapMonthStr + 1) {
              monthDate.push('闰' + calendar.toChinaMonth(leapMonthStr));
            }
            monthDate.push(calendar.toChinaMonth(i));
          }
          //如果当前月份是闰月
          if (leapMonthStr == month) {
            //更新天数
            for (var i = 1; i <= calendar.leapDays(year); i++) {
              dayData.push(calendar.toChinaDay(i));
            }
          } else {
            //更新天数
            for (var i = 1; i <= calendar.monthDays(year, month); i++) {
              dayData.push(calendar.toChinaDay(i));
            }
          }
        } else {
          //更新月份
          for (var i = 1; i <= 12; i++) {
            monthDate.push(calendar.toChinaMonth(i));
          }
          //更新天数
          for (var i = 1; i <= calendar.monthDays(year, month); i++) {
            dayData.push(calendar.toChinaDay(i));
          }
        }
      }
      this.dayArr = dayData;
      this.monthArr = monthDate;

      this.$nextTick(() => {
        this.scrollTarget[1].refresh(); //更新滚动盒子
        this.scrollTarget[2].refresh(); //更新滚动盒子
      });
      this.canSwitch = true;
      return dayData.length;
    },
    //按钮选择公历还是农历
    getSelectType: function(idx) {
      if (idx === this.selectIndex) return;
      this.selectIndex = idx;
      //如果选择了农历
      if (idx) {
        this.changeToLunarDate();
      } else {
        this.changeToSolarDate();
      }
    },
    //返回完整的日期字符串，形如 公历 1900年1月1日 时辰不清楚
    getAllDateStr: function(status) {
      var yearStr = this.yearArr[this.selectArr[0]];
      var monthStr = this.monthArr[this.selectArr[1]];
      var dayStr = this.dayArr[this.selectArr[2]];
      var hourStr = this.hourArr[this.selectArr[3]];
      var dateType = this.selectIndex ? '农历' : '公历';
      
      //如果有日期传进来
      if(this.birthDate == '' && !status){
        this.selectDateStr = this.defaultStr;        
      }else{
        //如果是农历
        if (this.selectIndex) {
          this.selectDateStr = dateType + ' ' + yearStr + '年' + monthStr + dayStr + ' ' + hourStr;
        } else {
          this.selectDateStr =
            dateType + ' ' + yearStr + '年' + monthStr + dayStr + '日' + ' ' + hourStr;
        }
      }
    },
    /**
     * @func
     * @desc  处理日期，类似 1992/1/1 -1 这种带有指定日期和时辰的，-1表示时辰不清楚，其它的对应 0 - 23时
     * @param {String} str - 需要处理的日期
     * @returns {Object} - 返回处理好的日期对象
     * @returns {Object.lunarDate} - chooseDate使用户选择的公历日期，带有时辰
     * @returns {Object.noPoint} - noPoint是用户选择的时辰是确定的时间（0），还是时辰不清楚（1）
     */
    dealCalendarTime(yIndex, mIndex, dIndex, hIndex) {
      var nopoint = 0; //默认有明确时辰
      var hourStr = '';

      if (hIndex == 0) {
        hourStr = '00:00';
        nopoint = 1; //不清楚时辰
      } else {
        //传入的时辰索引小于10时，需要添加0
        if (hIndex < 10) {
          hourStr = '0' + (hIndex - 1) + ':00';
        } else {
          hourStr = hIndex - 1 + ':00';
        }
      }

      var curYear = yIndex + 1900;
      var curMonth = 0;
      //如果是农历
      var leapMonthStr = calendar.leapMonth(curYear); //如果是0表示没有闰月，其它的则是润几月
      if (this.selectIndex && leapMonthStr && mIndex >= leapMonthStr) {
        curMonth = mIndex;
      } else {
        curMonth = mIndex + 1;
      }

      var isLeap = this.monthArr[mIndex].indexOf('闰') != -1 ? true : false; //本月是闰月

      var curDay = dIndex + 1;

      var curDate = curYear + '-' + curMonth + '-' + curDay; //当前传过来的日期
      var solarDate = '';
      var lunarDate = '';
      //如果当前选择的是农历，需要转换成公历
      if (this.selectIndex) {
        var dealLunarDate = calendar.lunar2solar(curYear, curMonth, curDay, isLeap);
        solarDate = dealLunarDate.sYear + '-' + dealLunarDate.sMonth + '-' + dealLunarDate.sDay;
        lunarDate = curDate;
      } else {
        var dealSolarDate = calendar.solar2lunar(curYear, curMonth, curDay);
        solarDate = curDate;
        lunarDate = dealSolarDate.lYear + '-' + dealSolarDate.lMonth + '-' + dealSolarDate.lDay;
      }

      return {
        solarDate: solarDate + ' ' + hourStr, //公历日期
        lunarDate: lunarDate + ' ' + hourStr,
        noPoint: nopoint, //时辰是否确定，0是有确定时辰，1是时辰不确定
        isSolar: this.selectIndex == 1 ? false : true,
        isLeapMonth: isLeap,
        sendDate: solarDate + ' ' + (hIndex - 1), //公历日期
        dateStr: this.selectDateStr
      };
    },
    //隐藏日历组件
    hideCalendar: function() {
      this.isShow = false;
    },
    //显示日历组件
    showCalendar: function() {
      this.isShow = true;
      this.$nextTick(function() {
        //此处显示之后必须刷新一次，不然显示之后滚动不了
        this.scrollTarget[0].refresh();
        this.scrollTarget[1].refresh();
        this.scrollTarget[2].refresh();
        this.scrollTarget[3].refresh();
        //如果默认隐藏，则必须修复滚动的位置
        this.scrollTarget[0].scrollTo(0, -this.itemHeight * this.selectArr[0]);
        this.scrollTarget[1].scrollTo(0, -this.itemHeight * this.selectArr[1]);
        this.scrollTarget[2].scrollTo(0, -this.itemHeight * this.selectArr[2]);
        this.scrollTarget[3].scrollTo(0, -this.itemHeight * this.selectArr[3]);
      });
    },
    //确认按钮点击
    confirmDate: function() {
      if (!this.canSwitch) return;
      this.getAllDateStr(true);

      var result = this.dealCalendarTime(
        this.selectArr[0],
        this.selectArr[1],
        this.selectArr[2],
        this.selectArr[3]
      );
      //向父组件传递选择的日期信息
      this.$emit('getSelectDate', result);
      this.hideCalendar();
    }
    //不再需要滚动的时候，可以销毁滚动，这样可以释放一些内存
    //暂时没有使用这个方法
    //			destroyScroll: function() {
    //				var arr = this.scrollTarget;
    //				var len = arr.length;
    //				for(var i = 0; i < len; i++) {
    //					arr[i].destroy();
    //					arr[i] = null;
    //				}
    //			}
  }
};
</script>

<style lang="less">
@import './calendar.less';
</style>